package com.rover.service.system;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rover.dao.BaseDao;
import com.rover.entity.system.Resource;
import com.rover.entity.system.Role;
import com.rover.entity.system.RoleResource;

@Service
@Transactional
public class RoleResourceService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao<RoleResource> roleResourceDao;

	@Autowired
	private ResourceService resourceService;

	@Autowired
	private RoleService roleService;

	/*
	 * 根据角色Id获取最小的一个资源id
	 * 
	 * @roles 角色id编号列表
	 */
	// @SuppressWarnings("unchecked")
	// @Transactional(readOnly = true)
	// public Long getFistResourceID(List<Long> roles) {
	// String hql =
	// "select parentId,resource_ID from RoleResource  where role_ID in(:alist) group by parentId,resource_ID order by parentId,resource_ID";
	// Query query = roleResourceDao.getCurrentSession().createQuery(hql);
	// query.setParameterList("alist", roles);
	//
	//
	// if (li.size() <= 0) {
	// return 0l;
	// } else
	// return li.get(0);
	// }

	/*
	 * 根据角色Id获取第一组parentId的resource_ID
	 * 
	 * @roles 角色id编号列表
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Long> getFistResourceID(List<Long> roles) {
		String hql = "select r.parentId,r.id from RoleResource rr,Resource r  where rr.resource_ID=r.id and  rr.role_ID in(:alist) group by r.parentId,r.id order by r.parentId,r.id";
		Query query = roleResourceDao.getCurrentSession().createQuery(hql);
		query.setParameterList("alist", roles);
		List<Long> liValue = new ArrayList<Long>();
		List<Object[]> li = query.list();
		int iCount = li.size();
		Object[] obj = null;
		// 记录第一条数据parentId的值
		String strFirst = "";
		for (int i = 0; i < iCount; i++) {
			obj = li.get(i);
			if(i==0)
				strFirst = obj[0].toString();
			if (strFirst.equals(obj[0].toString())) {
				liValue.add(Long.valueOf(obj[1].toString()));
			} else {
				break;
			}
		}
		return liValue;

	}

	@Transactional
	public void initData() {
		if (roleResourceDao.count("select count(*) from RoleResource") == 0) {
			Role role = roleService.getList().get(0);
			List<Resource> resources = resourceService.getAllResources();
			for (Resource resource : resources) {
				RoleResource roleResource = new RoleResource();
				roleResource.setResource_ID(resource.getId());
				roleResource.setRole_ID(role.getAddById());
				this.roleResourceDao.save(roleResource);
			}
		}
	}

}
